package cn.tedu.supermarket.controller;

import cn.tedu.supermarket.entity.*;
import cn.tedu.supermarket.mapper.AddressMapper;
import cn.tedu.supermarket.service.IAddressService;
import cn.tedu.supermarket.service.IOrdersService;
import cn.tedu.supermarket.service.impl.IAddressServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class AddressController {
    @Autowired
    IAddressService addAddress;
    @Autowired
    AddressMapper addressMapper;


    //遍历并显示地址信息
    @RequestMapping("/selAddress")
    public String sel(HttpSession session, Model model){
        if (session.getAttribute("user")!=null){
            User user = (User) session.getAttribute("user");
            List<Address> list = addressMapper.selAddressByUserId(user.getId());
            model.addAttribute("list",list);
            return "buy_user/address";
        }
        return "buy_user/buserLogin";
    }

    //页面跳转
    @RequestMapping("/add_Address")
    public String add(){
        return "buy_user/addAddress";
    }

    //检查输入框输入的信息是否正确
    @RequestMapping("/addressCheck")
    @ResponseBody
    public String check(AddressVO addressVO,HttpSession session){
        if (session.getAttribute("user")!=null){
            User user = (User) session.getAttribute("user");
            addressVO.setUserId(user.getId());
            Integer rows = addressMapper.selectAddress(addressVO);
             if("".equals(addressVO.getName())){
                return "请输入姓名!";
            } else if (!addressVO.getPhone().matches("^1\\d{10}$")){
                return "手机号错误!";
            }else if ("".equals(addressVO.getAddress())){
                return "请输入地址!";
            }else if (rows!=null){
                return "地址已存在";
            }
        }
        return String.valueOf(0);
    }

    //添加地址到数据库
    @RequestMapping("/addAddress")
    @ResponseBody
    public String add(AddressVO addressVO, HttpSession session){
        User user = (User) session.getAttribute("user");
        addressVO.setUserId(user.getId());
        Integer rows = addAddress.addAddress(addressVO);
        return String.valueOf(rows);
    }

    //删除地址
    @RequestMapping("/deleteAddress")
    public String delete(int id,HttpSession session){
        if (session.getAttribute("user")!=null){
            addressMapper.deleteById(id);
            return "redirect:selAddress";
        }
        return "buy_user/buserLogin";
    }

}
